package a_doubleWrite;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合总和,无重复元素，可重复使用其中元素
 * 输入：candidates = [2,3,6,7], target = 7,
 * 所求解集为：
 * [
 * [7],
 * [2,2,3]
 * ]
 *
 * @author: luolidong
 * @create: 2021-07-18 10:20
 * @version: 1.0
 */
public class L39 {
    List<List<Integer>> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        back_track(candidates, target, new ArrayList<>(), 0, 0);
        return list;
    }

    public void back_track(int[] candidates, int target, List<Integer> clist, int index, int sum) {
        if (index >= candidates.length || sum > target) return;
        if (sum == target) {
            list.add(new ArrayList<>(clist));
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            sum += candidates[i];
            clist.add(candidates[i]);
            back_track(candidates, target, clist, i, sum);
            clist.remove(clist.size() - 1);
            sum -= candidates[i];
        }
    }

    public static void main(String[] args) {
        L39 l39 = new L39();
        List<List<Integer>> list = l39.combinationSum(new int[]{2, 3, 6, 7}, 7);
        System.out.println(list);
    }
}
